package org.starapp.core.utils;

import java.io.IOException;
import java.io.Writer;

import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
import com.thoughtworks.xstream.io.json.JsonWriter;

public class JsonUtils {
	
	private final static ObjectMapper mapper= new ObjectMapper();
	static{
		mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
	}
	
	public static String bean2xml(Object bean) {
		XStream xstream = new XStream();
		xstream.alias(bean.getClass().getSimpleName(), bean.getClass());
		return xstream.toXML(bean);
	}

	public static Object xml2Bean(Class clazz, String xml) {
		XStream xstream = new XStream();
		xstream.alias(clazz.getSimpleName(), clazz);
		Object bean = xstream.fromXML(xml);
		return bean;
	}
	public static String bean2Json(Object bean) {
		XStream xstream = new XStream(		
				new JsonHierarchicalStreamDriver() {
			        public HierarchicalStreamWriter createWriter(Writer out) {
			            return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE);
			        }
			    });
		return xstream.toXML(bean);
	}

	public static <T> T json2Bean(String jsonString, Class<T> clazz) {
		if (StringUtils.isEmpty(jsonString)) {
			return null;
		}
		try {
			return mapper.readValue(jsonString, clazz);
		} catch (IOException e) {
			return null;
		}
	}
	
	
	@Deprecated
	private static Object json2Bean(Class clazz, String json) {
		XStream xstream = new XStream(new JettisonMappedXmlDriver());
		StringBuffer sb=new StringBuffer("{\"");
		sb.append(clazz.getName());
		sb.append("\":");
		sb.append(json);
		sb.append("}");
		System.out.println(sb.toString());
		Object bean = xstream.fromXML(sb.toString());
		return bean;
	}
	
}
